#include "user_global.h"
#include "crc.h"
#include <string.h>
#include "stdlib.h"
#include "device_usart.h"
#include "user_device.h"
#include "usart.h"
#include "user_config.h"
#include "tim.h"
#include "speed_cntr.h"
#include "modbus.h"


void HAL_UART_RxCpltCallback(UART_HandleTypeDef huart)
{
    if(huart == USART0)
    {
        if(!REN0)
            return;
        uart0_rx_pending = 1;
        if (timer_flag_get(TIMER5, TIMER_FLAG_UP))
        {
            uart0_len = 0;
        }
        timer_counter_value_config(TIMER5, 65536-2000);
        timer_flag_clear(TIMER5, TIMER_FLAG_UP);
        uart0_buf[UART0_BUF_MASK & uart0_len++] = (uchar)usart_data_receive(USART0);

        uart0_timestamp = timer_counter_read(TIMER5);
    }
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef huart)
{
    if(huart == USART0)
    {
        if(uart0_len)
        {
            usart_data_transmit(USART0, *uart0_tx_ptr++);
            --uart0_len;
        }
        else{
            uart0_tx_pending = 0;
            usart_interrupt_disable(USART0, USART_INT_TBE);
        }
    }
}

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef htim)
{
    uint8_t role = 255;
    // static uint32_t motor_subdiv_compensation[MACHINE_COUNT] = {0};
    switch (htim)
    {
    case TIMER1:
        role = S1;
        break;
    case TIMER0:
        role = S2;
        break;
    case TIMER11:
        role = S3;
        break;
    case TIMER13:
        role = S4;
        break;
    case TIMER6:
        ++system_tick.UU16;
        break;
    default:
        break;
    }

    if (role == 255)
        return;

    speed_update(role);

}
